/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.common.util;

import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.util.Validator;
import com.apache.client.UctProtoclClient;
import com.apache.passport.common.PassportHelper;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.SendService;
import com.apache.portal.common.oscache.OsCacheManager;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.ConfigUtil;
import com.apache.tools.OsUtils;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.*;

/**
 * description:  portal工厂类
 *
 * @author Hou Dayu 创建时间：2016-8-22
 */
public class PortalPubFactory {

    private static PortalPubFactory instance;

    private Map<String, PortalPlugin> plugins = new HashMap<String, PortalPlugin>();

    private Map<String, SendService> sends = new HashMap<String, SendService>();

    private PortalPubFactory() {

    }

    public static PortalPubFactory getInstance() {
        if (null == instance) {
            instance = new PortalPubFactory();
        }
        return (instance);
    }

    public PortalPlugin getPlugin(String key) {
        return plugins.get(key);
    }

    public void setPlugin(String key, PortalPlugin value) {
        plugins.put(key, value);
    }

    public void setSends(String key, SendService value) {
        if (ToolsUtil.isEmpty(sends.get(key))) {
            this.sends.put(key, value);
        }
    }

    public SendService getSends(String key) {
        return sends.get(key);
    }

    @SuppressWarnings("rawtypes")
    public Map<String, Object> getMethodParams(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String reqIp = RequestTools.getIp(request);
        map.put("Client-IP", reqIp);
        Set keSet = request.getParameterMap().entrySet();
        try {
            for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
                Map.Entry me = (Map.Entry) itr.next();
                String ok = String.valueOf(me.getKey());
                Object ov = me.getValue();
                String value = "";
                if (ov instanceof String[]) {
                    String[] vls = (String[]) ov;
                    value = vls[0];
                } else {
                    value = String.valueOf(ov);
                }
                if (StrUtil.isNotNull(value)) {
                    String str = new String(value.getBytes("iso8859-1"), "iso8859-1");
                    if (value.equals(str)) {
                        value = str;
                    }
                    map.put(ok, value);
                }
            }
        } catch (Exception e) {
        }
        map.put("sysPass", ConfigUtil.getInstance().interfacePass());
        return map;
    }

    /**
     * 随即生成最大值以内的随机数
     *
     * @param maxNum 设定的随即最大数值
     * @return 返回随即最大限制以内的随机值
     */
    public static String getRandomNumber(int maxNum) {
        int intRd = 0; //存放随机数
        Random rdm = new Random();
        String num = "";
        for (int i = 0; i < maxNum; i++) {
            intRd = Math.abs(rdm.nextInt()) % maxNum + 1;
            num += String.valueOf(intRd);
        }
        return num;
    }

    /**
     * 生成随机数
     *
     * @param type 1 数字 2 字母 3 数字+字母
     * @param maxNum 位数
     * @param choice 字母大小写--》如果type为1和3的时候使用  （65大写97L小写）
     * @return
     */
    public static String getRandomStr(String type, int maxNum, int choice) {
        String str = "";
        Random random = new Random();
        for (int i = 0; i < maxNum; i++) {
            //纯数字
            if (type.equals("1")) {
                str += String.valueOf(random.nextInt(10));
            } else if (type.equals("2")) {//纯字母
                str += (char) (choice + random.nextInt(26));
            } else if (type.equals("3")) {//数字和字母
                boolean b = random.nextBoolean();
                if (b) {//字符串
                    str += (char) (choice + random.nextInt(26));
                } else {//数字
                    str += String.valueOf(random.nextInt(10));
                }
            } else {//默认为数字
                str += String.valueOf(random.nextInt(10));
            }
        }
        if(str.startsWith("0")){
            StringBuffer sb = new StringBuffer(str);
            sb.replace(0,1,"1");
            return sb.toString();
        }else {
            return str;
        }
    }

    /**
     * 获取本机ip地址
     *
     * @return 返回本机的IP地址
     */
    public static String getLocalIp() {
        String localIp = null;
        try {
            if ("linux".equals(OsUtils.getSystemType())) {
                localIp = getLinuxIP();
            } else {
                localIp = InetAddress.getLocalHost().getHostAddress();
            }
        } catch (UnknownHostException e) {
            return "127.0.0.1";
        }
        return localIp;
    }

    private static String getLinuxIP() {
        String localIp = "127.0.0.1";
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                String name = ni.getName();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    String Ip = ((InetAddress) ips.nextElement()).getHostAddress();
                    if (!"127.0.0.1".equals(Ip) && ("eth0".equalsIgnoreCase(name) || "eth1"
                            .equalsIgnoreCase(name)) && Ip.indexOf(":") == -1) {
                        localIp = Ip;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return localIp;
    }

    public boolean JudgeIsMoblie(HttpServletRequest request) {
        boolean isMoblie = false;
        String mobileType = request.getParameter("userAgent");
        String randCode = request.getParameter("userKeys");
        if (StrUtil.isNotNull(mobileType) || StrUtil.isNotNull(randCode)) {
            return true;
        }

        if (request.getHeader("User-Agent") != null) {
            String dd = request.getHeader("User-Agent");
            isMoblie = IsModel.check(dd);
            // 判断是否为移动端访问
            //				if (isMoblie) {
            //					log.info("移动端访问");
            //				} else {
            //					log.info("pc端访问");
            //				}
        }
        return isMoblie;
    }

    public LoginUser getLoginUser(HttpServletRequest request) {
        return getLoginUser(request, "", "");
    }

    public LoginUser getLoginUser(HttpServletRequest request, String tokenId, String userAgent) {
        LoginUser loginUser = null;
        boolean isMobile = true;
        if (StrUtil.isNull(userAgent)) {
            isMobile = JudgeIsMoblie(request);
        }
        if (isMobile) {
            String tokenid = StrUtil.doNull(request.getParameter("tokenId"), tokenId);
            String tokenCookie = PassportHelper.getInstance().getCurrCookie(request);
            tokenid = StrUtil.doNull(tokenid, tokenCookie);
            if (Validator.isNull(tokenid))
                return null;
            loginUser = OsCacheManager.getInstance().getLoginUser(tokenid);
            if (ToolsUtil.isEmpty(loginUser)) {
                loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(tokenid);
                OsCacheManager.getInstance().putLoginUser(tokenid, loginUser);
            }
        } else {
            loginUser = PBOSSOTools.getLoginUser(request);
        }
        return loginUser;
    }

    /**
     * description:  获取系统接口注册信息
     *
     * @param sysEname:funds钱包;seq序列;info动态表单;wcm网站;audit日志;atta附件库;dict数据字典
     */
    public InterfaceRegister getRpcInfo(String sysEname) {
        if ("funds".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("funds", "funds_server_url", "funds_server_port");
        } else if ("net".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("net", "net_server_url", "net_server_port");
        } else if ("ius".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("ius", "ius_server_url", "ius_server_port");
        } else if ("sbm".equals(sysEname)) {
            return getInterfaceRegister("sbm_server_url", "sbm_server_port",
                    "/sbm/service/doService.action");
        } else if ("seq".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("seq", "info_release_url", "info_release_port");
        } else if ("info".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("info", "info_release_url", "info_release_port");
        } else if ("wcm".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("wcm", "info_release_url", "info_release_port");
        } else if ("audit".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("audit", "audit_server_url", "audit_server_port");
        } else if ("atta".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("atta", "attaServer_ip", "attaServer_port");
        } else if ("member".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("member", "member_server_url", "member_server_port");
        } else if ("dict".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("dict", "dictServer_ip", "dictServer_port");
        } else if ("uct".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("uct", "uctServer_ip", "uctServer_port");
        } else if ("sso".equals(sysEname)) {
            return getSsoRegister();
        } else if ("rpc".equals(sysEname)) {
            return UctProtoclClient.getInstance()
                    .getInterfaceRegister("rpc", "rpc_service_ip", "rpc_service_port");
        }
        return null;
    }

    public boolean isExites(String beanId) {
        if (StrUtil.isNull(beanId))
            return false;
        String cacheKey = "interfaceRegister_" + beanId;
        return LoadCacheFactory.getInstance().getCacheManager("").checkCacheObject(cacheKey);
    }

    public String getBeanId(String datasourceName) {
        String beanId = "iusService";
        if (StrUtil.isNotNull(datasourceName)) {
            if ("cms".equals(datasourceName)) {
                beanId = "websiteService";
            } else {
                beanId = datasourceName + "Service";
                if (!isExites(beanId) || "memberService".equals(beanId)) {
                    beanId = "iusService";
                }
            }
        }
        return beanId;
    }

    /**
     * 进行RPC接口注册的 IP/地址 和 端口的配置定义
     *
     * @return
     */
    private InterfaceRegister getInterfaceRegister(String urlKey, String portKey,
            String urlSubfix) {
        InterfaceRegister register = new InterfaceRegister();
        if (StrUtil.isNull(ConfigUtil.getInstance().getValueByKey("registry_protocol"))) {
            String reqUrl = ConfigUtil.getInstance().getValueByKey(urlKey);
            String infoUrl = reqUrl + urlSubfix;
            if (reqUrl.startsWith("https:")) {
                register.setCallType("https");
                register.setAddress(infoUrl);
            } else if (reqUrl.startsWith("http:")) {
                register.setCallType("http");
                register.setAddress(infoUrl);
            } else {
                String port = ConfigUtil.getInstance().getValueByKey(portKey);
                register.setAddress(reqUrl);
                register.setPort(port);
                register.setCallType("socket");
            }
        } else {
            register.setCallType("socket");
        }
        return register;
    }

    private InterfaceRegister getSsoRegister() {
        InterfaceRegister register = new InterfaceRegister();
        String type = ToolsUtil.getInstance().getValueByKey("req_type");
        if ("socket".equals(type)) {
            String ip = ToolsUtil.getInstance().getValueByKey("check_url");
            String port = ToolsUtil.getInstance().getValueByKey("check_port");
            register.setAddress(ip);
            register.setPort(port);
            register.setCallType("socket");
        } else {
            String ssoPath = ToolsUtil.getInstance().getValueByKey("req_url");
            register.setAddress(ssoPath);
            if (ssoPath.startsWith("https:"))
                register.setCallType("https");
            else {
                register.setCallType("http");
            }
        }
        return register;
    }

}
